using BootstrapBlazorApp.Server.LLMs.api;
using Newtonsoft.Json;

namespace BootstrapBlazorApp.Server.LLMs.prompt;

public class FewShotChatPromptTemplate 
{
    private List<Dictionary<string, string>> Examples { get; init; } = [];
    private List<IBaseMessage> MessagesList { get; init; } = [];

    public static FewShotChatPromptTemplate FromMessages(List<IBaseMessage> messages,
        string examples)
    {
        var examplesList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(examples) ??
                           throw new InvalidOperationException();
        return new FewShotChatPromptTemplate { MessagesList = messages, Examples = examplesList };
    }

   

    public List<IBaseMessage> ToMessageList()
    {
        List<IBaseMessage> exampleList = [];
        foreach (var example in Examples)
        {
            foreach (var kvp in example)
            {
                foreach (var message in MessagesList.Where(message => message.Content.Contains($"{{{kvp.Key}}}")))
                {
                    message.Content = message.Content.Replace($"{{{kvp.Key}}}", kvp.Value);
                }
            }

            exampleList.AddRange(MessagesList);
        }

        return exampleList;
    }
}
